// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
//@ts-ignore
import getMessage from 'ts-msg-handler'
import { activityApi } from '../../../api/activity'
import { uploadFiles } from '../../../api/file'
import { $event } from '../../../utils'
import { GlobalData } from '/store/state'
// import { activityApi } from '/api/activity'

Page({
  data: {
    isFullScreen: GlobalData.isFullScreen,
    cropper: '' as any,
    logoCropper: '' as any,
    creating: false,
    bgParams: {
      width: 181,
      height: 253,
      max_width: 500,
      max_height: 714,
      export_scale: 1,
      disable_rotate: true,
      disable_ratio: true,
      limit_move: true,
      src: '' as string,
      show: false,
      scale: 1,
      imgSrc: '' as any,
    },
    typeData: [] as any[],
    title: '',
    detail: '',
    date: '',
    location: '',
    type: 0,
    price: 0 as number | string,
    /** 页面展示的时间格式 */
    dateShow: '',
    /** 详细地址 */
    address: '',
    isEditor: false,
    id: 0,
    /** 发布状态，防止抖动点击 */
    publishing: false,
  },
  async onLoad(query: { type: string }) {
    this.setData({
      isFullScreen: GlobalData.isFullScreen,
      // @ts-ignore
      cropper: this.selectComponent('#image-cropper'),
    })
    const navData = (await activityApi.getActivityClassify()).data
    this.setData({
      typeData: navData,
      type: navData[0].id,
    })
    /** 编辑 */
    if (+query.type === 1) {
      const pages = getCurrentPages()
      const lastPage = pages[pages.length - 2]
      const lastPageData = lastPage.data
      this.setData({
        [`bgParams.imgSrc.url`]: lastPageData.activity.avatar.url,
        id: lastPageData.activity.id,
        title: lastPageData.activity.title,
        detail: lastPageData.activity.content,
        type: lastPageData.activity.category.id,
        dateShow: lastPageData.activity.date.replace('00:00:00', ''),
        location: lastPageData.activity.area,
        address: lastPageData.activity.address,
        price: lastPageData.activity.expense > 0 ? lastPageData.activity.expense : 0,
        isEditor: true,
      })
      wx.setNavigationBarTitle({
        title: '编辑活动',
      })
    }
  },
  handleBgTap() {
    wx.chooseImage({
      sizeType: ['compressed'],
      success: ({ tempFilePaths: { [0]: path } }) => {
        this.setData({
          bgParams: {
            ...this.data.bgParams,
            src: path,
            show: true,
          },
        })
      },
    })
  },
  /** 取消选择图片 */
  cancel() {
    this.setData({
      bgParams: {
        ...this.data.bgParams,
        show: false,
      },
    })
  },
  loadimage() {
    wx.hideLoading()
    this.data.cropper.imgReset()
  },
  clickcut(e: any) {
    //图片预览
    wx.previewImage({
      current: e.detail.url, // 当前显示图片的http链接
      urls: [e.detail.url], // 需要预览的图片http链接列表
    })
  },
  submitBg() {
    this.data.cropper.getImg((obj: any) => {
      this.setData({
        bgParams: {
          ...this.data.bgParams,
          imgSrc: obj,
          show: false,
        },
      })
    })
  },
  /** 标题 */
  inputTitle(e: WechatMiniprogram.CustomEvent) {
    const {
      detail: { value },
    } = e
    this.setData({
      title: value,
    })
  },
  /** 详情 */
  toEditor() {
    wx.navigateTo({
      url: '/pages/editor/editor?type=activity',
    })
  },
  /** 日期 */
  bindDateChange(e: WechatMiniprogram.CustomEvent) {
    const {
      detail: { value },
    } = e
    if (new Date().getTime() - new Date(value).getTime() > 0) {
      wx.showToast({
        title: '活动日期必须大于当前日期',
        icon: 'none',
        duration: 1000,
      })
      return
    }
    const date = value + ' 00:00:00'
    this.setData({
      date,
      dateShow: value,
    })
  },
  /** 价格 */
  inputPrice(e: WechatMiniprogram.CustomEvent) {
    const {
      detail: { value },
    } = e
    this.setData({
      price: value * 100,
    })
  },
  /** 分类 */
  chooseType(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { id },
      },
    } = e
    this.setData({
      type: id,
    })
  },
  toLocaltion() {
    wx.navigateTo({
      url: '/pages/activity/location/location',
    })
  },
  /** 发布 */
  async toSubmit() {
    const {
      data: {
        bgParams,
        type,
        title,
        detail,
        date,
        dateShow,
        location,
        price,
        address,
        isEditor,
        publishing,
      },
    } = this
    // 如果发布中，防止多次点击
    if (publishing) return
    if (
      !bgParams.imgSrc.url ||
      !title ||
      !detail ||
      !dateShow ||
      !(location || address) ||
      price === ''
    ) {
      wx.showToast({
        title: `${!bgParams.imgSrc.url
            ? '请选择封面'
            : !title
              ? '请输入活动标题'
              : !detail
                ? '请编辑活动详情'
                : !dateShow
                  ? '请选择活动日期'
                  : price === ''
                    ? '请输入价格'
                    : '请选择活动地址'
          }`,
        icon: 'none',
        duration: 1000,
      })
      return
    }
    if (title.length < 2) {
      wx.showToast({
        title: '请输入至少两个汉字的标题',
        icon: 'none',
      })
      return
    }
    wx.showLoading({
      title: this.data.isEditor ? '修改中' : '创建中',
    })
    this.setData({
      publishing: true,
    })
    try {
      const { node } = bgParams.imgSrc.width
        ? await uploadFiles(bgParams.imgSrc.url)
        : bgParams.imgSrc.url
      const data = {
        title,
        category_id: type,
        avatar: node,
        date: isEditor ? dateShow + ' 00:00:00' : date,
        content: detail,
        area: location,
        address: address,
        expense: price,
      }
      this.data.isEditor
        ? await activityApi.editorActivity(this.data.id, data)
        : await activityApi.creatActivity(data)
      wx.hideLoading()
      wx.showToast({
        title: this.data.isEditor ? '修改成功' : '创建成功',
        icon: 'none',
        duration: 1000,
      })
      $event.emit('activityChange')
      setTimeout(() => {
        wx.navigateBack({ delta: 1 })
      }, 1000)
    } catch (error) {
      this.setData({
        publishing: false,
      })
      wx.hideLoading()
      wx.showToast({
        title: `${getMessage(error.data).getMessage()}`,
        icon: 'none',
      })
    }
  },
})
